(function($)
{
    var opts = null;
    var gridBody = null;
    var that = this;
        
    $.fn.gridlite = function(options)
    {
      var tah = 0;
      opts = $.extend(true, {}, $.fn.gridlite.defaults, options);
      
      return this.each(function()
      {
        var element = $(this);
        
        fetchData();
        renderHeader(element);
        renderBody(element);
        
        // bind events
        $(this).bind('updateGrid', updateGrid);
      });
    
    };
        
    // private functions
    function updateGrid()
    {
        var element = $(this);
        fetchData();
        emptyGrid(element);
        renderHeader(element);
        renderBody(element);
    };
      
    function fetchData()
    {
        $.ajax(
        {
        	type: opts.jsonReader.reqType,
        	async: false,
        	url: opts.jsonReader.url,
        	data: {rowCount: opts.jsonReader.rowCount},
        	dataType: opts.jsonReader.dataType,
        	success: processReturnedData,
        	error: handleDataError
        });
    };
    
    function processReturnedData(data, textStatus)
    {
    	gridBody = '<tbody>';
    	for(var row in data[opts.jsonReader.root])
    	{
    		var dataItem = data['rows'][row];
    		gridBody += '<tr>';
    		
    		for(var colNum in opts.colModel)
    		{
    			var col = opts.colModel[colNum];	
    			var colVal = dataItem[col.jsonMap] ?  dataItem[col.jsonMap] : '';
    			if(dataItem[col.formatter])
    			{
    				colVal = col.formatter(colVal);
    			}
    			gridBody += '<td>' + colVal  + '</td>';
    		}
    		
    		gridBody += '</tr>';
    	}
    	gridBody += '</tbody>';
    };
    
    function handleDataError(XMLHttpRequest, textStatus, errorThrown)
    {
    	alert('your ajax call got messed up (error): ' + errorThrown + ' , no grid for you!');
    };
    
    function renderHeader(element)
    {
    	var gridHeader = '<thead><tr>';
    	for(var colNum in opts.colModel)
    	{
    		var col = opts.colModel[colNum]
    		gridHeader += '<th>' + col.name + '</th>';
    	}
    	gridHeader += '</tr></thead>';	
    	element.append(gridHeader);
    };
    
    function renderBody(element)
    {
    	element.append(gridBody);
    };
    
    function emptyGrid(element)
    {
    	element.html('');
    };
       
    // plugin defaults
    $.fn.gridlite.defaults =
    {
        width: '100%',
        jsonReader: 
        {
          reqType: 'GET',
        	dataType: 'json',
        	rowCount: 25
        },
        gridFooter: '<tfoot></tfoot>',
        pager: null
    };
      
})(jQuery);